<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入退货单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procurementmanagement:return:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['procurementmanagement:return:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['procurementmanagement:return:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="sn" width="150px" />
      <el-table-column label="入库单编号" align="center" prop="warehouseEntrySn" width="150px" />
      <el-table-column label="部门名称" align="center" prop="deptName" width="150px"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" width="150px"/>
      <el-table-column label="供应商名称" align="center" prop="supplierName" width="150px"/>
      <el-table-column label="经手人名称" align="center" prop="handleByName" width="150px"/>
      <el-table-column label="退货时间" align="center" prop="returnTime" width="150px"/>
      <el-table-column label="状态" align="center" prop="status" width="150px"/>
      <el-table-column label="审核人" align="center" prop="auditBy" width="150px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['procurementmanagement:return:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['procurementmanagement:return:submit']"
          >提交</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleWithdraw(scope.row)"
            v-hasPermi="['procurementmanagement:return:withdraw']"
          >撤回</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['procurementmanagement:return:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['procurementmanagement:return:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商退货对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="编号" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入编号"  style="width: 220px" disabled/>
        </el-form-item>
        <el-form-item label="入库单编号" prop="warehouseEntrySn">
          <el-button
            @click="handleEntryDialog"
            style="background-color: blue; color: white;"
          >选择</el-button>
          {{ form.warehouseEntrySn || '请选择入库单' }}
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader
            v-model="form.deptId"
            :options="deptTree"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择所属部门"
            @change="handleDeptChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="供应商名称" prop="supplierName">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleSupplierDialog"
          > {{ form.supplierName || '请选择供应商' }}</el-button>
        </el-form-item>
        <el-form-item label="相关合同" prop="purchasePlanId">
          <el-button
            @click="handleProcurementPlanDialog"
            style="background-color: blue; color: white;"
          > 选择</el-button>{{ form.contractSn || '请选择相关合同' }}
        </el-form-item>
        <el-form-item label="经手人">
          <el-cascader
            v-model="form.handleById"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择编制人"
            @change="handleCreatorChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="附件" prop="attachment">
          <el-input v-model="form.attachment" placeholder="请输入附件"  style="width: 220px"/>
        </el-form-item>
        <el-form-item label="退货时间" prop="returnTime">
          <el-date-picker
            clearable
            v-model="form.returnTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退货时间"
            @change="handleDateChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 相关合同选择器弹出窗口 -->
    <el-dialog :visible.sync="planListDialogVisible" title="选择相关合同" width="1000px">
      <el-table :data="planList">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedContractId"
              :label="scope.row.id"
              @change="handleContractRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="合同编号"></el-table-column>
        <el-table-column prop="supplierName" label="供应商"></el-table-column>
        <el-table-column prop="signTime" label="签订日期"></el-table-column>
        <el-table-column prop="contractStatus" label="合同状态"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="planListDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmContractSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog :visible.sync="auditDialogVisible" title="审核退货单" width="600px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="退货单编号">
          <el-input v-model="auditForm.sn" :disabled="true" />
        </el-form-item>
        <el-form-item label="退货时间">
          <el-input v-model="auditForm.returnTime" :disabled="true" />
        </el-form-item>
        <el-form-item label="仓库">
          <el-input v-model="auditForm.warehouseName" :disabled="true" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="auditForm.supplierName" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleReject">审核驳回</el-button>
        <el-button type="primary" @click="confirmAudit">审核通过</el-button>
      </div>
    </el-dialog>

    <!-- 供应商选择器弹出窗口 -->
    <el-dialog :visible.sync="supplierDialogVisible" title="选择供应商" width="1000px">
      <el-table :data="supplierList">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedSupplierId"
              :label="scope.row.id"
              @change="handleSupplierRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="customName" label="供应商名称"></el-table-column>
        <el-table-column prop="customSn" label="供应商编码"></el-table-column>
        <el-table-column prop="productionAddress" label="地址"></el-table-column>
        <el-table-column prop="transfer" label="传真"></el-table-column>
        <el-table-column prop="linkman" label="联系人"></el-table-column>
        <el-table-column prop="telephone" label="电话"></el-table-column>
        <el-table-column prop="email" label="电子邮件"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSupplierSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 入库单选择器弹出窗口 -->
    <el-dialog :visible.sync="entryListDialogVisible" title="选择入库单" width="1000px">
      <el-table :data="entryList" v-loading="loadingEntries">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedEntryId"
              :label="scope.row.id"
              @change="handleEntryRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="入库单号" width="180"></el-table-column>
        <el-table-column prop="entryTime" label="入库时间" width="180"></el-table-column>
        <el-table-column prop="supplierName" label="供应商"></el-table-column>
        <el-table-column prop="deptName" label="部门名称"></el-table-column>
        <el-table-column prop="warehouseName" label="仓库"></el-table-column>
      </el-table>

      <pagination
        v-show="entryTotal>0"
        :total="entryTotal"
        :page.sync="entryQueryParams.pageNum"
        :limit.sync="entryQueryParams.pageSize"
        @pagination="getEntryList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="entryListDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEntrySelection">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listReturn, getReturn, delReturn, addReturn, updateReturn } from "@/api/procurementmanagement/return";
import {
  getCompiler,
  getDeptTree, getPlan,
  getSupplierList,
  getsupplierListBid, listPlan,
} from "@/api/procurementmanagement/plan";
import {listContract ,getContract} from "@/api/procurementmanagement/contract";
import { listEntry } from "@/api/procurementmanagement/entry";

export default {
  name: "Return",
  data() {
    return {
      usedEntrySns: [], // 存储已被退货单使用的入库单编号
      entryListDialogVisible: false,
      selectedEntryId: null,
      selectedEntry: null,
      entryList: [],
      entryTotal: 0,
      entryQueryParams: {
        pageNum: 1,
        pageSize: 10,
        status: '审核通过'
      },
      loadingEntries: false, // 入库单加载状态
      warehouseEntryOptions: [], // 入库单选项
      selectedContractId: null,
      selectedSupplierId: null,
      selectedContract: null,
      supplierDialogVisible: false,
      planListDialogVisible: false,
      auditDialogVisible: false,
      //二级部门
      planList:[],
      deptTree: [],
      //制表人
      personList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      supplierList: [],
      // 供应商退货表格数据
      returnList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      auditForm: {
        id: '',
        sn: '', // 退货单编号
        returnTime: '', // 退货时间
        warehouseName: '', // 仓库名称
        supplierName: '', // 供应商名称
        contractId: '',
        warehouseEntryId:''
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        deptId: null,
        warehouseEntryId: null,
        warehouseEntrySn: null,
        warehouseId: null,
        supplierId: null,
        supplierSn: null,
        deptName: null,
        warehouseName: null,
        supplierName: null,
        contractId: null,
        contractSn: null,
        handleById: null,
        handleByName: null,
        attachment: null,
        returnTime: null,
        status: null,
        auditBy: null,
        auditRemark: null,
        creator: null,
        updater: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseEntryList(); // 获取入库单列表
  },
  methods: {
    refreshWarehouseEntries() {
      this.getWarehouseEntryList();
    },
    // 处理入库单选择变化
    handleWarehouseEntryChange(sn) {
      if (!sn) {
        // 清空选择时重置相关字段
        this.form.warehouseEntryId = null;
        this.form.deptId = null;
        this.form.deptName = null;
        this.form.warehouseId = null;
        this.form.warehouseName = null;
        this.form.supplierId = null;
        this.form.supplierName = null;
        this.form.handleById = null;
        this.form.handleByName = null;
        this.form.contractId = null;  // 新增：清空合同ID
        this.form.contractSn = null;  // 新增：清空合同编号
        return;
      }

      // 查找选中的入库单
      const selectedEntry = this.warehouseEntryOptions.find(item => item.value === sn)?.data;
      if (selectedEntry) {
        // 自动填充相关字段
        this.form.warehouseEntryId = selectedEntry.id;
        this.form.deptId = selectedEntry.deptId;
        this.form.deptName = selectedEntry.deptName;
        this.form.warehouseId = selectedEntry.warehouseId;
        this.form.warehouseName = selectedEntry.warehouseName;
        this.form.supplierId = selectedEntry.supplierId;
        this.form.supplierName = selectedEntry.supplierName;
        this.form.handleById = selectedEntry.handledById;
        this.form.handleByName = selectedEntry.handledByName;

        // 新增：自动填充相关合同信息
        if (selectedEntry.contractId) {
          this.form.contractId = selectedEntry.contractId;
          this.form.contractSn = selectedEntry.contractSn;
        }
      }
    },
    // 获取入库单列表
    getWarehouseEntryList() {
      this.loadingEntries = true;
      listEntry({
        pageSize: 1000,
        status: '审核通过',  // 只查询状态为"审核通过"的入库单
        includeContract: true  // 假设API支持这个参数来包含合同信息
      }).then(response => {
        // 获取所有已使用的入库单编号
        const usedEntrySns = this.returnList.map(item => item.warehouseEntrySn);

        this.warehouseEntryOptions = response.rows
          .filter(item => item.status === '审核通过' && !usedEntrySns.includes(item.sn))
          .map(item => ({
            label: `${item.sn} | ${item.supplierName} | ${item.deptName} | ${item.warehouseName}`,
            value: item.sn,
            data: item // 保存完整数据
          }));
      }).finally(() => {
        this.loadingEntries = false;
      });
    },
    /** 查询供应商退货列表 */
    getList() {
      this.loading = true;
      listReturn(this.queryParams).then(response => {
        this.returnList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        deptId: null,
        warehouseEntryId: null,
        warehouseEntrySn: null,
        warehouseId: null,
        supplierId: null,
        supplierSn: null,
        deptName: null,
        warehouseName: null,
        supplierName: null,
        contractId: null,
        contractSn: null,
        handleById: null,
        handleByName: null,
        attachment: null,
        returnTime: null,
        status: null,
        auditBy: null,
        auditRemark: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 打开供应商选择器
    handleSupplierDialog() {
      this.getSupplierList();
      this.supplierDialogVisible = true;
    },
    handleSupplierRadioChange(row) {
      this.selectedSupplier = row;
      this.selectedSupplierId = row.id; // 手动设置选中的供应商ID
    },
    // 确认选择供应商
    confirmSupplierSelection() {
      if (this.selectedSupplier) {
        this.form.supplierName = this.selectedSupplier.customName;
        this.form.supplierId = this.selectedSupplier.id;
        this.supplierDialogVisible = false;
      } else {
        this.$message.warning("请选择一个供应商");
      }
    },
    // 获取供应商列表
    getSupplierList() {
      getSupplierList().then(response => {
        this.supplierList = response.data;
      });
    },
    // 处理供应商行点击事件
    handleSupplierRowClick(row) {
      this.selectedSupplier = row; // 保存当前选中的供应商
    },
    // 确认选择供应商
    confirmSupplierSelection() {
      if (this.selectedSupplier) {
        // 调用后端接口获取供应商详情
        getsupplierListBid(this.selectedSupplier.id).then(response => {
          this.form.supplierName = response.data.customName; // 假设返回的数据中包含供应商名称
          this.form.supplierId = this.selectedSupplier.id; // 保存供应商 ID 到表单
          this.supplierDialogVisible = false; // 关闭弹窗
        }).catch(error => {
          console.error("获取供应商详情失败", error);
          this.$message.error("获取供应商详情失败");
        });
      } else {
        this.$message.warning("请选择一个供应商");
      }
    },
    // 提交操作
    handleSubmit(row) {
      this.$modal.confirm('是否确认提交退货单编号为"' + row.sn + '"的数据项？').then(() => {
        return updateReturn({
          ...row,
          status: '已提交' // 更新状态为已提交
        });
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList(); // 刷新列表
      }).catch(() => {});
=======
        this.$modal.confirm('是否确认提交退货单编号为"' + row.sn + '"的数据项？').then(() => {
            return updateReturn({
                ...row,
                status: '已提交' // 更新状态为已提交
            });
        }).then(() => {
            this.$modal.msgSuccess("提交成功");
            this.getList(); // 刷新列表
        }).catch(() => {});
>>>>>>> master
    },

    // 撤回操作
    handleWithdraw(row) {
      this.$modal.confirm('是否确认撤回退货单编号为"' + row.sn + '"的数据项？').then(() => {
        return updateReturn({ ...row, status: '未提交' }); // 更新状态为未提交
      }).then(() => {
        this.$modal.msgSuccess("撤回成功");
        this.getList(); // 刷新列表
      }).catch(() => {});
    },

    // 审核操作
handleAudit(row) {
    this.auditForm = {
        id: row.id,
        sn: row.sn,
        returnTime: row.returnTime,
        warehouseName: row.warehouseName,
        supplierName: row.supplierName,
        auditRemark: row.auditRemark || '',

        warehouseEntryId: row.warehouseEntryId,
        contractId: row.contractId,
        deptId: row.deptId,

        handleById: row.handleById,
        supplierId: row.supplierId,
        warehouseId: row.warehouseId
      };
      this.auditDialogVisible = true;
    },
=======
    };
    this.auditDialogVisible = true;
},

    // 打开入库单选择对话框
    handleEntryDialog() {
      this.entryListDialogVisible = true;
      this.getEntryList();
    },

    // 获取入库单列表（用于选择）
    getEntryList() {
      this.loadingEntries = true;

      // 首先获取所有退货单，收集已使用的入库单编号
      listReturn({ pageSize: 1000 }).then(returnResponse => {
        this.usedEntrySns = returnResponse.rows.map(item => item.warehouseEntrySn);

        // 然后获取入库单列表，并过滤掉已使用的
        listEntry({
          ...this.entryQueryParams,
          status: '审核通过' // 只查询审核通过的入库单
        }).then(entryResponse => {
          this.entryList = entryResponse.rows.filter(entry =>
            !this.usedEntrySns.includes(entry.sn)
          );
          this.entryTotal = entryResponse.total;
          this.loadingEntries = false;
        }).catch(error => {
          this.loadingEntries = false;
          console.error("获取入库单失败", error);
        });
      }).catch(error => {
        this.loadingEntries = false;
        console.error("获取退货单失败", error);
      });
    },

    // 处理入库单行选择
    handleEntryRadioChange(row) {
      this.selectedEntry = row;
      this.selectedEntryId = row.id;
    },

    // 确认选择入库单
    confirmEntrySelection() {
      if (this.selectedEntry) {
        this.form.warehouseEntryId = this.selectedEntry.id;
        this.form.warehouseEntrySn = this.selectedEntry.sn;

        // 自动填充相关字段
        this.form.deptId = this.selectedEntry.deptId;
        this.form.deptName = this.selectedEntry.deptName;
        this.form.warehouseId = this.selectedEntry.warehouseId;
        this.form.warehouseName = this.selectedEntry.warehouseName;
        this.form.supplierId = this.selectedEntry.supplierId;
        this.form.supplierName = this.selectedEntry.supplierName;
        this.form.handleById = this.selectedEntry.handledById;
        this.form.handleByName = this.selectedEntry.handledByName;

        // 自动填充相关合同信息
        if (this.selectedEntry.contractId) {
          this.form.contractId = this.selectedEntry.contractId;
          this.form.contractSn = this.selectedEntry.contractSn;
        }

        this.entryListDialogVisible = false;
      } else {
        this.$message.warning("请选择一个入库单");
      }
    },

    // 审核驳回操作
    handleReject() {
      this.$modal.confirm('是否确认驳回退货单编号为"' + this.auditForm.sn + '"的数据项？').then(() => {
        return updateReturn({
          ...this.auditForm,
          status: '未提交',
          auditBy: null // 清除审核人
        }); // 更新状态为未提交
      }).then(() => {
        this.$modal.msgSuccess("审核驳回成功");
        this.auditDialogVisible = false; // 关闭弹窗
        this.getList(); // 刷新列表
      }).catch(() => {});
    },

    // 审核通过操作
    confirmAudit() {
      this.$modal.confirm('是否确认审核通过退货单编号为"' + this.auditForm.sn + '"的数据项？').then(() => {

        return getReturn(this.auditForm.id).then(response => {
          const fullData = response.data;

          return updateReturn({
            ...fullData,
            status: '审核通过',
            auditBy: 'superadmin',
            auditRemark: this.auditForm.auditRemark || ''
          });
        });
      }).then(() => {
        this.$modal.msgSuccess("审核通过成功");
        this.auditDialogVisible = false;
        this.getList(); // 刷新列表
      }).catch(() => {});
        this.$modal.confirm('是否确认审核通过退货单编号为"' + this.auditForm.sn + '"的数据项？').then(() => {

            return getReturn(this.auditForm.id).then(response => {
                const fullData = response.data;

                return updateReturn({
                    ...fullData,
                    status: '审核通过',
                    auditBy: 'superadmin',
                    auditRemark: this.auditForm.auditRemark || ''
                });
            });
        }).then(() => {
            this.$modal.msgSuccess("审核通过成功");
            this.auditDialogVisible = false;
            this.getList(); // 刷新列表
        }).catch(() => {});
>>>>>>> master
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree();
      this.getCompiler();
      this.getEntryList(); // 使用新的获取方法

      // 设置默认值
      const now = new Date();
      this.form.returnTime = now.toISOString().slice(0, 10);
      this.form.status = '未提交';

      this.generateContractNumber(this.form.returnTime);
      this.open = true;
      this.title = "添加供应商退货";
    },

    // 处理日期变化事件
    handleDateChange(date) {
      if (date) {
        this.generateContractNumber(date); // 生成新的退货单编号
      }
    },

    // 生成退货单编号
    generateContractNumber(returnTime) {
      const prefix = "SR"; // 编号前缀
      const formattedDate = returnTime.replace(/-/g, ""); // 将日期格式化为 YYYYMMDD
      let seq = 1; // 默认序列号为 1

      // 假设从后端获取当天的合同数量
      this.getContractCountByDate(returnTime).then(count => {
        seq = count + 1; // 当天的合同数量加1
        const formattedSeq = String(seq).padStart(4, "0"); // 序列号格式化为 0001
        this.form.sn = `${prefix}${formattedDate}${formattedSeq}`; // 拼接编号
      });
    },

    // 修改采购计划对话框为合同对话框
    handleProcurementPlanDialog() {
      this.listContract();  // 调用获取合同列表的方法
      this.planListDialogVisible = true;
    },

    handleContractRadioChange(row) {
      this.selectedContract = row;
      this.selectedContractId = row.id;
    },

    confirmContractSelection() {
      if (this.selectedContract) {
        getContract(this.selectedContract.id).then(response => {
          const contractData = response.data;
          this.form.contractSn = contractData.sn;
          this.form.contractId = contractData.id;

          // 自动填充采购计划编号
          this.form.procurementPlanSn = contractData.procurementPlanSn ||
            contractData.planSn ||
            contractData.relatedPlanSn ||
            '';

          // 如果合同中有供应商信息，自动填充
          if (contractData.supplierName && !this.form.supplierName) {
            this.form.supplierName = contractData.supplierName;
            this.form.supplierId = contractData.supplierId;
          }

          this.planListDialogVisible = false;
          this.$message.success("合同选择成功");
        }).catch(error => {
          console.error("获取合同详情失败", error);
          this.$message.error("获取合同详情失败");
        });
      } else {
        this.$message.warning("请选择一个合同");
      }
    },

    // 获取当天的合同数量
    getContractCountByDate(date) {
      return new Promise((resolve, reject) => {
        listContract({ returnTime: date }).then(response => {
          resolve(response.total); // 返回当天的合同数量
        }).catch(error => {
          console.error("获取合同数量失败", error);
          resolve(0); // 如果失败，默认返回0
        });
      });
    },

    // 获取执行中的合同列表
    listContract() {
      this.loading = true;
      listContract({
        pageSize: 1000,
        contractStatus: '执行中'  // 只查询执行中的合同
      }).then(response => {
        this.planList = response.rows;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error("获取合同列表失败", error);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getReturn(id).then(response => {
        this.form = response.data;
        this.getDeptTree();
        this.getCompiler();
        this.getEntryList(); // 使用新的获取方法
        this.open = true;
        this.title = "修改供应商退货";
      });
    },
    // 获取部门树
    getDeptTree() {
      getDeptTree().then(response => {
        console.log(response.data)
        this.deptTree = response.data;
      });
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    handleDeptChange(value) {
      if (value.length > 0) {
        // 获取选中的最后一级部门的 ID
        const deptId = value[value.length - 1];
        // 根据 ID 查找对应的部门对象
        const selectedDept = this.findDeptById(this.deptTree, deptId);
        if (selectedDept) {
          this.form.deptId = selectedDept.id; // 保存子部门的 ID
          this.form.deptName = selectedDept.name; // 保存子部门的名称
          console.log(this.form.deptName, this.form.deptId);
        }
      } else {
        this.form.deptId = null;
        this.form.deptName = null;
      }
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.handledById = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.handledByName = selectedPerson.realName; // 保存编制人名称到表单
          console.log(this.form.handledByName, this.form.handledById);
        }
      } else {
        this.form.handledById = null;
        this.form.handledByName = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.refreshWarehouseEntries(); // Refresh the list after update
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.refreshWarehouseEntries(); // Refresh the list after add
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除供应商退货编号为"' + ids + '"的数据项？').then(function () {
        return delReturn(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('procurementmanagement/return/export', {
        ...this.queryParams
      }, `return_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 完全隐藏单选按钮的所有标签内容 */
.custom-radio ::v-deep .el-radio__label {
  display: none !important;
  width: 0;
  height: 0;
  overflow: hidden;
}

.el-select-dropdown__item {
  white-space: normal;
  line-height: 1.5;
  padding: 8px 20px;
}

.el-select-dropdown__item span {
  display: inline-block;
  width: 25%;
}
</style>
